package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.common.BaseResponse;
import com.common.ErrorCode;
import com.common.ResultUtils;
import com.constant.ChatType;
import com.domain.dto.UserInfo;
import com.domain.entity.*;
import com.domain.request.ApplyFriendRequest;
import com.domain.request.UserLoginRequest;
import com.domain.request.UserRegisterRequest;
import com.exception.BusinessException;
import com.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import static com.constant.UserConstant.AGREE;
import static com.constant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UsersService userService;
    @Autowired
    private ApplyFriendService applyFriendService;

    @Autowired
    private UserFriendService userFriendService;
    @Autowired
    private UserSessionService userSessionService;
    @Autowired
    private ChatMessageService chatMessageService;

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 根据多个标签获取用户
     *
     * @param tags
     * @return
     */
    @GetMapping("/tags")
    public BaseResponse<ArrayList<UserInfo>> getUserByTag(@RequestParam("tags") ArrayList<String> tags) throws ExecutionException, InterruptedException {
        return userService.getUserByTag(tags);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    /**
     * 更改用户信息
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        // 校验参数是否为空
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        int result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 根据用户id删除用户
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 获取最匹配的用户
     *
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, user));
    }

    /**
     * 根据用户名搜索用户
     *
     * @param username
     * @param request
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 好友申请
     *
     * @param applyFriendRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/friend/apply")
    public BaseResponse<Boolean> applyFriend(ApplyFriendRequest applyFriendRequest, HttpServletRequest httpServletRequest) {
        User loginUser = userService.getLoginUser(httpServletRequest);
        return userService.applyFriend(applyFriendRequest, loginUser.getId());
    }

    /**
     * 获取当前用户的好友申请列表
     *
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/friend/list")
    public BaseResponse<List<ApplyFriend>> getApplyFriendList(HttpServletRequest httpServletRequest) {
        User loginUser = userService.getLoginUser(httpServletRequest);
        return ResultUtils.success(userService.getApplyFriendList(loginUser.getId()));
    }

    /**
     * 更新申请好友状态/同意/不同意
     *
     * @param httpServletRequest
     * @return
     */
    @Transactional
    @PutMapping("/friend")
    public BaseResponse<Boolean> updateFriendStatus(Long id, Integer status, HttpServletRequest httpServletRequest) {
        long currentTimeMillis = System.currentTimeMillis();
        User loginUser = userService.getLoginUser(httpServletRequest);
        UpdateWrapper<ApplyFriend> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id).eq("apply_user_id", loginUser.getId()).set("status", status);
        applyFriendService.update(wrapper);
        //同意申请
        if (status == AGREE) {
            //更改好友列表
            UserFriend userFriend = getUserFriendData(id, loginUser);
            userFriendService.save(userFriend);
            //添加会话
            UserSession userSession = userSessionService.createUserSession(
                    id,
                    loginUser,
                    ChatType.PRIVATE,
                    ChatType.UN_STICKY,
                    currentTimeMillis,
                    currentTimeMillis);
            userSessionService.save(userSession);
            //添加申请信息
            ChatMessage applyChatMessage = createApplyChatMessage(id, loginUser);
            chatMessageService.save(applyChatMessage);
        }
        return ResultUtils.success(false);
    }

    private ChatMessage createApplyChatMessage(Long id, User loginUser) {
        ApplyFriend applyFriend = applyFriendService.getOne(new QueryWrapper<ApplyFriend>().eq("user_id", loginUser.getId()).eq("apply_user_id", id));
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSendTime(System.currentTimeMillis());
        chatMessage.setType(ChatType.PRIVATE);
        chatMessage.setText(applyFriend.getText());
        chatMessage.setReceiverId(id);
        chatMessage.setSenderId(loginUser.getId());
        return chatMessage;
    }


    private static UserFriend getUserFriendData(Long id, User loginUser) {
        long currentTimeMillis = System.currentTimeMillis();
        UserFriend userFriend = new UserFriend();
        userFriend.setUserId(loginUser.getId());
        userFriend.setFriendId(id);
        userFriend.setCreateTime(currentTimeMillis);
        return userFriend;
    }

}
